<?php

namespace Viettrans\BackBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\FormError;

/**
 * System controller.
 *
 * @Route("/bo/system")
 */
class SystemController extends Controller
{
    /**
     * @Route("/", name="bo_system_index")
     * @Template()
     */
    public function indexAction() {
		return array();
    }

    /**
     * @Route("/flush_cache", name="bo_system_flush_cache")
     * @Template()
     */
    public function flushCacheAction() {
		$symfonyRootPath = $this->container->getParameter('symfony_root_path');
		
		exec("rm -r $symfonyRootPath/app/cache/prod", $output, $res);
		
		if ($res) return new Response('KO');
		
		return new Response('OK');
    }
	
    /**
     * @Route("/modif_config", name="bo_system_modif_config")
     * @Template()
     */
    public function modifConfigAction() {
		$request = $this->get('request');
		$filePath = $request->get('filePath');

		$params = $this->parseConfigFile($filePath);

		return array('params' => $params);
    }	
	
	private function parseConfigFile($filePath) {
		# If file does not exist then show the error
		if (!file_exists($filePath)) throw new \Exception("The config file $filePath does not exist.");
		
		$lines = file($filePath);
		
		$content = array();
		
		$currentSegment = 'general';

		foreach($lines as $line) {
			$lineParsed = explode("=", $line);
			if (sizeof($lineParsed) < 2) continue;
			
			$paramName = trim($lineParsed[0]);
			$paramValue = trim($lineParsed[1]);
			
			if($paramName == '* segment') {
				$currentSegment = $paramValue;
				$content[$paramValue] = array();
				
			} else {
				$content[$currentSegment][$paramName] = $paramValue;
			}
		}
		
		return $content;
	}
}
